package vmcs.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import vmcs.entity.StoreItem;

/**
 * 
 * Abstract Change Manager for Store Item. 
 * 
 * Used as a reusable parent class for Drink Store Item Change Manager and Cash Store Item Change Manager. 
 * 
 * @author lai shiaw san
 *
 */
public abstract class StoreItemChangeManager {

    /**
     * Define an event that is triggered when store item quantity changes.
     */
    public static final int EVENT_QUANTITYCOINCHANGE = 1;
    public static final int EVENT_QUANTITYDRINKCHANGE = 2;
    public static final int EVENT_DRINKVALUECHANGE = 3;
    
    // notify all interested parties of the event

    public void notify(StoreItem storeItem, int event) {

        // check if this event has any interested observers
        if (!observerMap.containsKey(event)) {
            // no interested observers of the specified event, ignore!
            return;
        }

        // get all observers
        List< StoreItemObserver> observerList = observerMap.get(event);

        // notify all observers
        for (StoreItemObserver observer : observerList) {
            observer.update(storeItem, event);
        }
    }

    /**
     * Register an observer to be interested in a particular event.
     * @param observer
     * @param event
     */
    public void register(StoreItemObserver observer, int event) {
        // check if this event has any interested observers
        if (!observerMap.containsKey(event)) {
            // no interested observers of the specified event yet, create new list.
            observerMap.put(event, new ArrayList< StoreItemObserver>());
        }

        // get all observers
        List< StoreItemObserver> observerList = observerMap.get(event);

        // add observer to event
        observerList.add(observer);

        System.out.println("StoreItemChangeManager: Observer " + observer + " registered to receive updates of event " + event + " in change manager " + this);
    }
    /**
     * Map of event to list of observers. 
     * Observers of same event are added to same list. 
     */
    private final Map< Integer, List< StoreItemObserver>> observerMap = new HashMap< Integer, List< StoreItemObserver>>();
}
